<template>
  <div class="fileUploadList">
    <el-form :inline="true" :model="searchForm" size="small">
      <el-form-item label="日志类型">
        <el-select v-model="searchForm.type" style="width: 100%" clearable placeholder="请选择">
          <el-option :label="item.value" v-for="item in typeListLog" :value="item.id" :key="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间">
        <el-date-picker v-model="searchForm.pickertime" size="small" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="logSearch">日志收集</el-button>
        <el-button @click="search">刷新</el-button>
      </el-form-item>
    </el-form>
    <div class="contant">
      <el-table :data="tableData" style="width: 100%;" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
        :header-cell-style="{background:'#e5e5e5',color:'#000'}">
        <el-table-column prop="nodeId" label="设备标识" />
        <el-table-column prop="deviceId" label="设备ID" />
        <el-table-column prop="type" label="任务类型">
          <template slot-scope="{row}">
            {{ row.type | taskType(typeList) }}
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column prop="downloadPercentage" label="获取进度">
          <template slot-scope="{row}">
            <div style="display:flex">
              <el-progress :percentage="row.downloadPercentage" style="width:100%"></el-progress>
              <img src="../../assets/images/ld.gif" alt="" style="width:16px;height:16px" v-if="row.shellExcuteStatus==0">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="shellExcuteStatus" label="执行状态">
          <template slot-scope="{row}">
            <span v-if="row.shellExcuteStatus==0" style="color:#409EFF">执行中</span>
            <span v-if="row.shellExcuteStatus==1" style="color:#67C23A">成功</span>
            <span v-if="row.shellExcuteStatus==2" style="color:#F56C6C">失败</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon='el-icon-view' @click="viewDetail(scope.row)">详情</el-button>
            <el-button type="text" style="color: #f56c6c" size="mini" icon='el-icon-delete' @click="deleteTask(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align:right">
        <pagination v-show="pagination.total>0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
      </div>
    </div>
    <div class="showPo" v-show="dialogVisible">
      <div style="text-align: center">
        <div class="bg1">
          <div class="aaa-bgg"></div>
        </div>
        <div class="showPo_tip">
          <div class="showPo_tip_one">日志正在收集中...</div>
          <h3 class="showPo_tip_two">收集日志时需要一点时间，请稍后</h3>
        </div>
        <div class="poBtnC">
          <div class="poBtn" :title="`取消收集`" @click="cancelPd">
            取消收集
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="详情" :visible.sync="dialogVisibleDetail" width="80%" destroy-on-close :close-on-click-modal="false">
      <el-table :data="tableDataDetail" style="width: 100%;" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row :header-cell-style="{background:'#e5e5e5',color:'#000'}">
        <!-- <el-table-column type="selection" width="40" /> -->
        <el-table-column prop="deviceId" label="设备ID" />
        <el-table-column prop="name" label="文件名称" />
        <el-table-column prop="size" label="文件大小" :formatter="fileSizeFormatter" />
        <el-table-column prop="url" label="文件下载URL" />
        <el-table-column prop="createTime" label="上传时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon='el-icon-view' @click="handleDown(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 20px">
        <el-button @click="dialogVisibleDetail = false" size="small">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import * as api from '@/api/link/fileUpload'
import * as downRecordApi from '@/api/link/downRecord'
import { set } from 'nprogress'

export default {
  comments: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      dialogVisibleDetail: false,
      type: '',
      searchForm: {
        type: 'LogfileUpload'
      },
      typeListLog: [{
        value: '设备日志',
        id: 'LogfileUpload'
      }],
      typeOptions: [
        // 1 设备软件
        // 2 补丁
        // 3 初始化配置
        // 4 shell脚本
        // 5 组件公钥
        // 6 容器公钥
        // 7 应用公钥
        // 8 容器镜像包
        // 9 容器升级包
        // 10 应用文件
        // 11 终端升级包
        {
          value: '1',
          label: '设备软件'
        },
        {
          value: '2',
          label: '补丁'
        },
        {
          value: '3',
          label: '初始化配置'
        },
        {
          value: '4',
          label: 'shell脚本'
        },
        {
          value: '5',
          label: '组件公钥'
        },
        {
          value: '6',
          label: '容器公钥'
        },
        {
          value: '7',
          label: '应用公钥'
        },
        {
          value: '8',
          label: '容器镜像包'
        },
        {
          value: '9',
          label: '容器升级包'
        },
        {
          value: '10',
          label: '应用文件'
        },
        {
          value: '11',
          label: '终端升级包'
        }
      ],
      multipleSelection: [],
      tableData: [],
      tableDataDetail: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      curTitle: "新增",
      timer: null,
      timer1: null,
      timeValue: 10,
      deviceId: '',
      clicks: 0,
      typeList: [
        { value: 'DeviceState', label: "获取设备信息" },
        { value: 'SoftwareLoad', label: "设备升级" },
        { value: "PatchLoad", label: "补丁升级" },
        { value: 'SoftwareLoadStatus', label: "系统文件下载状态查询" },
        { value: 'CfgfileLoad', label: "配置文件升级" },
        { value: 'CfgfileLoadStatus', label: "配置文件升级状态查询" },
        { value: 'SystemReboot', label: "重启设备" },
        { value: 'LogfileUpload', label: "设备日志收集" },
        { value: 'LogfileUploadNotify', label: "设备日志收集结果上报" },
        { value: 'LogfileUploadStatus', label: "设备日志收集状态查询" },
        { value: 'ShellScriptLoad', label: "应用升级" },
        { value: 'ShellScriptLoadNotify', label: "可执行文件执行结果上报" },
        { value: 'ShellScriptLoadStatus', label: "可执行文件执行状态查询" },
        { value: 'EthStatus', label: "网络接口信息查询" },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
    }
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight
      return curHeight - 280
    }
  },
  created() {
    // this.searchForm.deviceId = this.$route.query.nodeId
    this.deviceId = this.$route.query.nodeId
    this.getPageList()
  },
  mounted() {

  },
  destroyed() {
    window.clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    viewDetail(row) {

      this.dialogVisibleDetail = true
      api.checkDetail({ fileName: row.fileId }).then(res => {

        if (res.code == '200') {
          this.tableDataDetail = res.data ? [res.data] : []
        }
      })
    },
    deleteTask(row) {
      
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteTask(row.id).then(res => {
          
          if (res.code == '200') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.search()
          }
        })
      })

    },
    // 复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getPageList() {
      this.search()
    },
    search() {
      let flag = false
      const p = Object.assign({
        type: this.searchForm.type,
        startTime: this.searchForm.pickertime && this.searchForm.pickertime[0],
        endTime: this.searchForm.pickertime && this.searchForm.pickertime[1]
      }, this.pagination, { deviceId: this.deviceId })
      api.page(p).then(resp => {

        this.$nextTick(() => {
          this.tableData = resp.data.records
          this.pagination.total = resp.data.total
          this.tableData.some(item => {
            if (item.shellExcuteStatus == 0) {
              flag = true
              return true
            }
          })
          if (flag && !this.timer && !this.clicks) {
            this.checkDetail(resp.data.records[0].messageId)
          }
        })
      })
    },
    logSearch() {
      // this.dialogVisible = true
      if (!this.searchForm.type) {
        return this.$message({
          type: 'warning',
          message: '请选择日志类型!'
        });
      }
      let flag = false
      this.tableData && this.tableData.some(item => {
        if (item.shellExcuteStatus == 0) {
          flag = true
          return true
        }
      })
      if (flag) {
        this.$message({
          type: 'warning',
          message: '正在收集中,请稍等!'
        });
      } else {
        var row = this.$route.query
        
        var p = {
          iotDevices: [{
            clientId: row.deviceId,
            nodeId: row.nodeId,
          }],
          type: this.searchForm.type,
          taskId: "123",
          tenantId: row.tenantId,
          startTime: this.searchForm.pickertime && this.searchForm.pickertime[0],
          endTime: this.searchForm.pickertime && this.searchForm.pickertime[1],
        }
        downRecordApi.commandIssue(p).then(res => {
          if (res.code == '200') {
            this.clicks = 1
            this.getCom(res.data.messageId)
          }
        })
      }
    },
    //倒计时
    timeDown() {
      let timeValue = this.timeValue;
      this.timer1 = setInterval(() => {
        if (timeValue > 1) {
          timeValue--;
          this.timeValue = timeValue;
        } else {
          clearInterval(this.timer1);
          this.timer1 = null
          this.timeValue = 0
        }
      }, 1000);
    },
    getCom(id) {
      this.search()
      this.checkDetail(id)
    },
    checkDetail(id) {
      let self = this
      api.checkLogProgress(id).then(res => {
        if (res.code == '200') {
          if (res.data.shellExcuteStatus == 0) {
            this.timer = setTimeout(() => {
              if (this.timeValue > 1) {
                self.checkDetail(id)
              }
            }, 3000)
          } else {
            window.clearTimeout(this.timer)
            this.timer = null
            // this.tableData = []
            this.search()
          }
        }
      })
    },
    cancelPd() {
      this.dialogVisible = false
      clearInterval(this.timer);
      this.timer = null
      clearInterval(this.timer1);
      this.timer1 = null
      // this.timeValue = 10
      // this.$message({
      //   type: 'warning',
      //   message: '已取消收集!'
      // });
    },
    handleDown(row) {
      const url1 = row.url.replace('http://112.74.59.73:9528/', 'https://ota-web.xhszmc.com/');
      window.open(url1, '_blank');
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteById(row.id).then(resp => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          if ((this.pagination.total - 1) % this.pagination.pageSize == 0) {
            if (this.pagination.page > 1) {
              this.pagination.page = this.pagination.page - 1;
            }
          }
          this.search();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    fileSizeFormatter(row, index) {
      var filesize = row.size
      var size = ''
      if (filesize < 0.1 * 1024) { //小于0.1KB，则转化成B
        size = filesize.toFixed(2) + "B"
      } else if (filesize < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
        size = (filesize / 1024).toFixed(2) + "KB"
      } else if (filesize < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
        size = (filesize / (1024 * 1024)).toFixed(2) + "MB"
      } else {                                            //其他转化成GB
        size = (filesize / (1024 * 1024 * 1024)).toFixed(2) + "GB"
      }
      var sizeStr = size + "";                        //转成字符串
      var index = sizeStr.indexOf(".");                    //获取小数点处的索引
      var dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
      if (dou == "00") {                                //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size;
    }
  },
  filters: {

    taskType(val, typeList) {
      let arr = typeList.find(item => {
        return item.value == val
      })
      if (arr) {
        return arr.label
      } else {
        return ''
      }
    }
  },
}
</script>

<style scoped lang="scss">
.fileUploadList {
  padding: 20px;
  .showPo {
    position: fixed;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    display: flex;
    justify-content: center;
    align-items: center;
    top: 0;
    left: 0;
    z-index: 922;
  }
  .showPo > div {
    width: 300px;
    background: white;
    padding-bottom: 20px;
    border-radius: 20px;
  }
  .showPo div {
    font-size: 12px;
  }

  .bg1 {
    display: flex;
    align-content: center;
    align-items: center;
    justify-items: center;
    justify-content: center;
    position: relative;
  }
  .aaa-bgg {
    margin-top: 20px;
    background-image: url("../../assets/images/13.gif");
    width: 250px;
    height: 115px;
    background-size: 100% 100%;
  }
  .poBtnC {
    margin-top: 30px;
    display: flex;
    align-content: center;
    align-items: center;
    justify-items: center;
    justify-content: center;
    margin-bottom: 10px;
    .poBtn {
      min-width: 120px;
      padding: 0 10px;
      border-radius: 20px;
      background: #3267d5;
      color: white;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
    }
  }
}
.fileUpload {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
</style>
